package com.example.admin.controller;

import cn.hutool.core.util.ObjectUtil;
import com.example.admin.service.CategoryService;
import com.example.xo.common.pojo.Category;
import com.example.xo.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author liguoping
 */
@RestController
@Slf4j
@RequestMapping("category")

public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping("add")
    public Result add(@RequestBody Category category) {
        log.info("{}", category);
        if (category.getCategoryName() == null ||
                category.getCategoryName().trim().length() == 0) {
            log.info("标题为空");
            return Result.error();
        }
        if (category.getCategoryName().length() > 20) {
            log.info("分类{}字符个数超过20", category.getCategoryName());
            return Result.error();
        }
        boolean res = categoryService.add(category);
        if (!res) {
            log.info("分类名字重复");
            return Result.error();
        }
        //返回添加成功
        return Result.success();
    }

    @GetMapping("findAll")
    public Result findAll() {
        List<Category> list = categoryService.findAll();
        return Result.success(list);
    }

    @GetMapping("{id}")
    public Result findById(@PathVariable String id) {
        Category category = categoryService.findById(id);
        return Result.success(category);
    }

    @PutMapping("update")
    public Result update(@RequestBody Category category) {
        //字符长度不能超过20
        if (category.getCategoryName().length() > 20) {
            //记录给程序员
            log.info("分类{}长度超过20个字", category.getCategoryName());
            return Result.error();
        }

        boolean res = categoryService.update(category);
        return Result.success(res);
    }

    @DeleteMapping("delete/{id}")
    public Result delete( @PathVariable String id) {
        return Result.success(categoryService.deleteById(id));
    }

    @GetMapping("findByName/{name}")
    public Result findByName(@PathVariable String name) {
        Category category = categoryService.findByName(name);
        return Result.success(category);
    }
}
